/*
* webide for education
*/
package com.webide.project.ctrl;

import com.webide.base.WebSocketServer;
import com.webide.core.entity.BeanRet;
import com.webide.core.exceptions.BaseException;
import com.webide.core.tools.FileUtil;
import com.webide.core.tools.redis.RedisUtils;
import com.webide.setting.entity.Setting;
import com.webide.setting.service.SettingSV;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 项目控制器
 *
 * @author berton
 */
@RestController
@RequestMapping("/project")
@Slf4j
@Api(value = "项目控制器", description = "项目控制器")
public class ProjectCtrl {

    @Resource
    protected RedisUtils redisUtils;


    @Resource
    private SettingSV settingSV;

    /**
     * 查询项目信息
     * <p>
     *
     * @param filePath 文件路径
     * @return BeanRet
     */
    @ApiOperation(value = "查询项目信息", notes = "查询项目信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文档路径", paramType = "query")
    })
    @GetMapping(value = "load")
    @ResponseBody
    public BeanRet load(String filePath) throws IOException {
        log.info(filePath);
        Map<String, Object> map = new HashedMap();
        map.put("type", "Directory");
        String projectName = settingSV.loadByK(Setting.Key.Project_Name.name()).getV();
        map.put("projectName", projectName);
        map.put("filePath", "smart-plant-iot");

        return BeanRet.create(true, "查询成功", map);
    }


    /**
     * 查询文件路径
     *
     * @param filePath 文件路径
     * @return BeanRet
     */
    @ApiOperation(value = "查询文件路径", notes = "查询文件路径")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filePath", value = "文档路径", paramType = "query")
    })
    @GetMapping(value = "/scan/path")
    @ResponseBody
    public BeanRet scanPath(String filePath) throws IOException {
        Assert.hasText(filePath, BaseException.BaseExceptionEnum.Empty_Param.toString());
        filePath =  "home/" + filePath;
        log.info("filePath::" + filePath);
        File file = new File(filePath);
        if (file.exists()) {
            if (file.isDirectory()) {
                //TODO  subStr配置到数据库或项目文件中
                List<Map<String, String>> mapList = FileUtil.sanDirFiles(filePath, "smart-plant-iot");
                return BeanRet.create(true, "查询一个详情信息", mapList);
            }

            if (file.isFile() && !filePath.contains(".jar")) {
                String fileStr = FileUtils.readFileToString(new File(filePath), "UTF-8");
                Map<String, Object> map = new HashedMap();
                map.put("fileStr", fileStr);
                return BeanRet.create(true, "查询一个详情信息", map);
            }
        } else {
            return BeanRet.create(filePath + "不存在或不是文件目录");
        }
        return BeanRet.create(true, "", filePath.replaceAll("/\\w*\\.jar", ""));
    }

    /**
     * 前端传递代码，通过ssh调用pitop服务器接口，运行代码，并日志信息
     *
     * @return BeanRet
     */
    @ApiOperation(value = "获取日志信息", notes = "获取日志信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "文档路径", paramType = "query")
    })
    @GetMapping(value = "/logs/{sid}")
    @ResponseBody
    public BeanRet logs(@PathVariable String sid) throws IOException {
        String path = "home/logs.txt";
        log.info("path:::" + path);
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)),
                    "UTF-8"));
            String lineTxt;
            while ((lineTxt = br.readLine()) != null) {
                WebSocketServer.sendInfo(lineTxt + "\n", sid);
                Random random = new Random();
                int randNumber = random.nextInt(500);
                Thread.sleep(randNumber);
            }
            br.close();
        } catch (Exception e) {
            log.info("read error");
        }
        return BeanRet.create(true, "Success");
    }


}
